package org.ly817.endurance.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * Created by LuoYu on 2018/3/4.
 */
@Configuration
public class SessionFactoryConfig {

    @Autowired()
    @Qualifier("dataSource") // 不止一个bean
    private DataSource dataSource;
    @Value("${mybatis.config_path}")
    private String configPath;
    @Value("${mybatis.mapper_path}")
    private String mapper;
    @Value("${mybatis.entity_package}")
    private String entityPackage;

    @Bean
    public SqlSessionFactoryBean getSessionFactory() throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(configPath));
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        String mapperPath = PathMatchingResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + mapper;
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources(mapperPath));
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setTypeAliasesPackage(entityPackage);
        return sqlSessionFactoryBean;
    }
}
